//
//  MTUserRegisterViewController.swift
//  MT
//
//  Created by ooops on 2020/4/4.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition
import Result
import Moya
import RxSwift

public typealias userRegisterSuccess = ((String, String) -> Void)

class MTUserRegisterViewController: BaseViewController {
    
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        .backgroundStyleTransparent
    }
    
    override func yp_navigationBarTintColor() -> UIColor! {
        UIColor(hex: 0xFFFFFF)
    }

    override func yp_navigationBackgroundColor() -> UIColor! {
        .clear
    }

    override func yp_navigationBackgroundImage(withIdentifier identifier: AutoreleasingUnsafeMutablePointer<NSString?>!) -> UIImage! {
        return nil
    }
    
    private lazy var provider: MTProvider<UserCenterApi> = {
        return MTProvider<UserCenterApi>(plugins: [])
    }()
    
    /// 账号 TextField
    var accTextField: UITextField?
    /// 密码 TextField
    var pwdTextField: UITextField?
    /// 校验密码框
    var validatePwdTextField: UITextField?
    /// 如果账号已存在
    private var userExsitBlock: userRegisterSuccess?
    
    /// 登录按钮
    lazy var registerButton: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor.theme.main
        btn.setTitle("注 册", for: .normal)
        btn.setTitleColor(UIColor.text.x161616, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 22
        btn.addTarget(self, action: #selector(register), for: .touchUpInside)
        return btn
    }()
    
    convenience init(_ block: userRegisterSuccess?) {
        self.init()
        self.userExsitBlock = block
    }
    
    override init() {
        super.init()
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    required public init(rounterParams params: Dictionary<String, Any>?) {
        fatalError("init(rounterParams:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        
    }
    
    private func setupUI() {
        let accTF = createTextField(withPlaceholder: "请输入邮箱")
        self.accTextField = accTF
        
        let pwdTF = createTextField(withPlaceholder: "请输入密码")
        pwdTF.isSecureTextEntry = true
        self.pwdTextField = pwdTF
        
        let validatePwdTF = createTextField(withPlaceholder: "请再次输入密码")
        validatePwdTF.keyboardType = .alphabet
        validatePwdTF.isSecureTextEntry = true
        self.validatePwdTextField = validatePwdTF
        
        self.view.addSubview(accTF)
        self.view.addSubview(pwdTF)
        self.view.addSubview(validatePwdTF)
        self.view.addSubview(registerButton)
        
        accTF.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(70)
            make.right.equalTo(self.view).offset(-70)
            make.top.equalTo(self.view.snp.centerY).offset(-80)
            make.height.equalTo(30)
        }
        
        pwdTF.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(accTF)
            make.top.equalTo(accTF.snp.bottom).offset(30)
        }
        
        validatePwdTF.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(accTF)
            make.top.equalTo(pwdTF.snp.bottom).offset(30)
        }
        
        registerButton.snp.makeConstraints { (make) in
            make.bottom.equalTo(view).offset(-ScreenBottomExtraOffset - 124)
            make.centerX.equalTo(view)
            make.width.equalTo(210)
            make.height.equalTo(44)
        }
        
    }
    
    
    @objc private func register() {
        
        ValidateData()
        
    }
    
    /// 检查数据合法性
    private func ValidateData() {
        
        /// 检查邮件合法
        if let acc = self.accTextField?.text {
            if !isValidEmail(testStr: acc) {
                AlertManager.presentAlertView(message: "请输入正确的邮箱")
                return
            }
        } else {
            AlertManager.presentAlertView(message: "请输入正确的邮箱")
            return
        }
        
        /// 验证密码
        if let pwd = self.pwdTextField?.text, pwd != "" {
            
            if isPasswordRuler(password: pwd) {
                AlertManager.presentAlertView(message: "请至少输入6为的字母数字组合密码")
                return
            }
            
            /// 校验两次密码是否一致
            if let validatePwd = self.validatePwdTextField?.text, validatePwd != "" {
                
                if pwd != validatePwd {
                    AlertManager.presentAlertView(message: "两次输入的密码不一致, 请重新输入")
                    return
                }
                
                if isPasswordRuler(password: validatePwd) {
                    AlertManager.presentAlertView(message: "请至少输入6位的字母数字组合密码")
                    return
                }
                
                /// 数据校验完毕
                //debugPrint("注册成功")
                self.userRegister(userName: self.accTextField!.text!, password: pwd)
                
            } else {
                AlertManager.presentAlertView(message: "请再次输入密码")
                return
            }
        } else {
            AlertManager.presentAlertView(message: "请输入密码")
            return
        }
        
    }
    
    private func userRegister(userName: String, password: String) {
        
        let parameter: [String : Any] = ["userName" : userName, "password" : password]
        MBProgressHUD_JChat.showLoading(self.view)
        provider.originRequest(.userRegister(parameter: parameter), callbackQueue: .global(), progress: nil) { [weak self] (result, _) in
            guard let weakSelf = self else { return }
//            DispatchQueue.main.async {
//                weakSelf.navigationController?.popToRootViewController(animated: false)
//            }
            switch result {
            case .success(let response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    DispatchQueue.main.async {
                        MBProgressHUD_JChat.dismiss(weakSelf.view)
                    }
                    if code == 200, let result = datas["result"] as? [String: Any] {
                        DispatchQueue.main.async {
                            self?.userExsitBlock?(userName, password)
                        }
                        /// 刷新用户模型
                        UserCenter.default.set(with: result)
                        DispatchQueue.main.async {
                            guard let status = UserCenter.default.userStatus, let sex = UserCenter.default.sex else { return }
                            if sex == 0 {
                                
                                if let name = UserCenter.default.userName, let pwd = UserCenter.default.userPassword {
                                    IMLoginManager.login(name, pwd, complete: {
                                        /// 设置用户模型
                                        UserCenter.default.set(with: result)
                                        DispatchQueue.main.async {
                                            AlertManager.presentAlertView(message: "登录成功", duration: 1) {
                                                UserStatusNavigate.push(from: weakSelf, withUserStatus: status)
                                            }
                                        }
                                    }) {
                                        UserCenter.default.clear()
                                        IMLoginManager.logout()
                                        DispatchQueue.main.async {
                                            AlertManager.presentAlertView(message: "登录失败")
                                        }
                                    }
                                } else {
                                    UserCenter.default.logout()
                                }
                                
                            } else {
                                DispatchQueue.main.async {
                                    let c = UIAlertController(title: "视频验证", message: "你将进入视频验证环节，是否进入", preferredStyle: .alert)
                                    let a1 = UIAlertAction(title: "是", style: .default) { (action) in
                                        UserStatusNavigate.push(from: weakSelf, withUserStatus: status)
                                    }
                                    let a2 = UIAlertAction(title: "否", style: .cancel) { (action) in
                                        weakSelf.navigationController?.popViewController(animated: true)
                                    }
                                    c.addAction(a1)
                                    c.addAction(a2)
                                    weakSelf.present(c, animated: true, completion: nil)
                                }
                            }
                        }
                    } else {
                        if code == 500 {
                            DispatchQueue.main.async {
                                MBProgressHUD_JChat.show(text: "用户已存在, 请登录", view: weakSelf.view)
                            }
                            DispatchQueue.main.after(2) {
                                self?.navigationController?.popToRootViewController(animated: true)
                                self?.userExsitBlock?(userName, password)
                            }
                        } else {
                            DispatchQueue.main.async {
                                MBProgressHUD_JChat.show(text: "注册失败", view: weakSelf.view)
                            }
                        }
                    }
                    
                }
                break
            case let .failure(error):
                DispatchQueue.main.async {
                    MBProgressHUD_JChat.dismiss(weakSelf.view)
                    AlertManager.presentAlertView(message: error.localizedDescription)
                }
                break
            }
        }
        
    }
    
    /// 密码强度校验 至少 6 数字字母组合
    private func isPasswordRuler(password:String) -> Bool {
        let passwordRule = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$"
        let regexPassword = NSPredicate(format: "SELF MATCHES %@",passwordRule)
        if regexPassword.evaluate(with: password) == true {
            return true
        }else
        {
            return false
        }
    }
    
    func isValidEmail(testStr:String) -> Bool {
        // debugPrint("validate calendar: \(testStr)")
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"

        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailTest.evaluate(with: testStr)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    private func createTextField(withPlaceholder placeholder: String) -> UITextField {
        let tf = UITextField()
        tf.font = PingFangSCRegularFont(14)
        tf.textColor = .black
        tf.tintColor = .black
        
        let astr = NSMutableAttributedString(string: placeholder)
        astr.setAttributes([NSAttributedString.Key.foregroundColor: UIColor.black.withAlphaComponent(0.8)], range: NSMakeRange(0, astr.length))
        tf.attributedPlaceholder = astr
        tf.textAlignment = .center
        
        let line = UIView()
        line.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        tf.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(tf)
            make.height.equalTo(0.5)
        }
        return tf
    }

}
